﻿using System;
using System.Xml;
using System.Xml.Schema;
using System.Collections.Generic;
using System.IO;

namespace LAPI.Core.Helpers
{
    public class XmlValidator
    {
        public IList<string> _errors = new List<string>();

        public XmlValidator() {
        }

        public bool Validate(string xsdFile, string xmlString)
        {
            TextReader xmlReader       = new StringReader(xmlString);
            XmlReaderSettings settings = new XmlReaderSettings();
            XmlSchemaSet set           = new XmlSchemaSet();

            _errors = new List<string>();

            set.Add(null, xsdFile);
            
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas        = set;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += new ValidationEventHandler(BooksSettingsValidationEventHandler);

            XmlReader items = XmlReader.Create(xmlReader, settings);

            while (items.Read()) { }

            return GetErrors().Count == 0;
        }

        public void BooksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Warning)
            {
                _errors.Add(e.Message);
            }
            else if (e.Severity == XmlSeverityType.Error)
            {
                _errors.Add(e.Message);
            }
        }

        public IList<string> GetErrors()
        { 
            return _errors;
        }
    }
}